package com.example.experiment_5;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText edName;
    private EditText edPhone;
    private Button btnAdd;
    private Button btnQuery;
    private Button btnUpdate;
    private Button btnDelete;
    private RecyclerView recyclerView;

    private final MySQLiteOpenHelper mySQLiteOpenHelper = new MySQLiteOpenHelper(MainActivity.this);
    private SQLiteDatabase db;
    private String name;
    private String phone;
    private final List<Contact> contacts = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        initView();

        btnAdd.setOnClickListener(this);
        btnQuery.setOnClickListener(this);
        btnUpdate.setOnClickListener(this);
        btnDelete.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_add) {
            getTextFromEditText();
            addContact(name, phone);
            showToast("添加成功");
        } else if (id == R.id.btn_query) {
            queryContact();
            // 创建适配器
            MyAdapter adapter = new MyAdapter(contacts);
            // 设置LayoutManager
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            // 设置适配器
            recyclerView.setAdapter(adapter);
            showToast("查询成功");
        } else if (id == R.id.btn_update) {
            getTextFromEditText();
            updatePhone(name, phone);
            showToast("修改成功");
        } else if (id == R.id.btn_delete) {
            getTextFromEditText();
            deleteContact(name);
            showToast("删除成功");
        }
    }

    private void initView() {
        edName = findViewById(R.id.ed_name);
        edPhone = findViewById(R.id.ed_phone);
        btnAdd = findViewById(R.id.btn_add);
        btnQuery = findViewById(R.id.btn_query);
        btnUpdate = findViewById(R.id.btn_update);
        btnDelete = findViewById(R.id.btn_delete);
        recyclerView = findViewById(R.id.recyclerView);
    }

    private void getTextFromEditText() {
        name = edName.getText().toString();
        phone = edPhone.getText().toString();
    }

    private void showToast(String info) {
        Toast.makeText(MainActivity.this, info, Toast.LENGTH_SHORT).show();
    }

    /**
     * 添加联系人
     * @param name 姓名
     * @param phone 电话号码
     */
    private void addContact(String name, String phone) {
        // 获取可读写SQLiteDatabase对象
        db = mySQLiteOpenHelper.getWritableDatabase();
        // 创建ContentValues对象
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("phone", phone);
        db.insert("contact", null, values); // SQLiteDatabase对象的insert方法会返回插入记录的id, 若有需要可在此处获取
        db.close();
    }

    /**
     * 查询联系人
     */
    private void queryContact() {
        contacts.clear();
        // 获取SQLite数据库
        db = mySQLiteOpenHelper.getReadableDatabase();
        // 构造查询语句
        String selectQuery = "SELECT * FROM contact";
        Cursor cursor = db.rawQuery(selectQuery, null);

        // 遍历查询结果
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact(
                        cursor.getString(cursor.getColumnIndexOrThrow("name")),
                        cursor.getString(cursor.getColumnIndexOrThrow("phone"))
                );
                contacts.add(contact);
            } while (cursor.moveToNext());
        }

        // 关闭cursor和数据库连接
        cursor.close();
        db.close();
    }

    /**
     * 修改联系人信息
     * @param name 待修改信息的联系人的姓名
     * @param phone 新电话号码
     */
    private void updatePhone(String name, String phone) {
        db = mySQLiteOpenHelper.getWritableDatabase();
        ContentValues values = new ContentValues();     // 要修改的数据
        values.put("phone", phone);
        db.update("contact", values, "name=?", new String[] {name});    // 更新并得到行数
        db.close();
    }

    /**
     * 删除联系人
     * @param name 待删除联系人的姓名
     */
    private void deleteContact(String name) {
        db = mySQLiteOpenHelper.getWritableDatabase();
        db.delete("contact", "name=?", new String[] {name});
        db.close();
    }

}